package com.itheima.ThreadTest.ThreadPool;

import com.itheima.ThreadTest.first.MyCallable;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

public class TestPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 核心线程池数量
        // 计算密集型 CPU核数 + 1
        // IO密集型 CPU核数 * 2
        ExecutorService pool = new ThreadPoolExecutor(
                3,
                5,
                8,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy() // 抛弃任务报异常
//                new ThreadPoolExecutor.DiscardPolicy() // 丢弃任务不抛异常
//                new ThreadPoolExecutor.DiscardOldestPolicy() // 抛弃队列中等待最久的任务
                new ThreadPoolExecutor.CallerRunsPolicy() // 主线程亲自调用
        );
        Runnable target = new MyRunnable();
        pool.execute(target);
        pool.execute(target);
        pool.execute(target);
        pool.execute(target);

        Future<String> f1 = pool.submit(new MyCallable(6));
        System.out.println(f1.get());
//        pool.shutdownNow(); // 立即关闭线程池
    }

    @Test
    public void testOtherPool() throws ExecutionException, InterruptedException {
        // 不推荐这样创建线程池，不要控制线程数量，容易资源耗尽
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Future<String> f1 = pool.submit(new MyCallable(6));
        Future<String> f2 = pool.submit(new MyCallable(6));
        Future<String> f3 = pool.submit(new MyCallable(6));
        Future<String> f4 = pool.submit(new MyCallable(6));
        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());
        System.out.println(f4.get());
    }
}
